package net.ib.mtalk.ui.buddy.group;

import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseActivity;
import net.ib.mtalk.database.DatabaseContract.GroupTable;
import net.ib.mtalk.database.helper.GroupDatabaseHelper;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddGroup extends BaseActivity implements OnClickListener{
	private EditText editText;
	private Context mContext;
	private String groupName;
	private int groupId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setContentView(R.layout.activity_add_group);
		
		mContext = this;
		
		if(getIntent() != null && getIntent().getExtras() != null) {
			Bundle bundle = getIntent().getExtras();
			groupName = bundle.getString(EditGroup.GroupName);
			groupId = bundle.getInt(EditGroup.GroupId);
		}
		
		editText = (EditText) findViewById(R.id.aag_edit);
		if(groupName != null){
			editText.setText(groupName);
		}
		
		Button ok = (Button) findViewById(R.id.aag_ok);
		if(groupId != 0){
			ok.setText(R.string.modify);
		}
		Button cancel = (Button) findViewById(R.id.aag_cancel);
		
		ok.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.aag_ok){
			String groupname = editText.getText().toString();
			if(groupname == null || groupname.equals("")){
				Toast.makeText(mContext, R.string.group_enter_group_name, Toast.LENGTH_SHORT).show();
			} else{
				if(groupId != 0){
					String selection = GroupTable.KEY_GROUP_NAME + "=?";
					Cursor cursor = getContentResolver().query(GroupTable.CONTENT_URI, GroupTable.PROJECTION, 
							selection, new String[]{groupname}, null);
					if(cursor.getCount() > 0){
						Toast.makeText(mContext, R.string.group_exist_group, Toast.LENGTH_SHORT).show();
					} else {
						GroupDatabaseHelper.updateGroup(mContext, groupId, groupname);
						finish();
					}
				} else{
					String selection = GroupTable.KEY_GROUP_NAME + "=?";
					Cursor cursor = getContentResolver().query(GroupTable.CONTENT_URI, GroupTable.PROJECTION, 
							selection, new String[]{groupname}, null);
					if(cursor.getCount() > 0){
						Toast.makeText(mContext, R.string.group_exist_group, Toast.LENGTH_SHORT).show();
					} else {
						GroupDatabaseHelper.insertGroup(mContext, groupname);
						finish();
//					Intent intent = getIntent();
//					startActivityForResult(intent, EditGroup.GroupCreate);
					}
				}
			}
		} else if(v.getId() == R.id.aag_cancel){
			finish();
		}
	}
}
